package com.yvan.demo.mvc;

import com.yvan.Conv;
import com.yvan.PageDb;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class PageDbResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (parameter.getParameterType() == PageDb.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Object arg = webRequest.getParameter("page");
        if (arg == null) {
            return new PageDb(false);
        }

        int page = Conv.NI(arg, 1);
        int start = Conv.NI(webRequest.getParameter("start"), 0);
        int limit = Conv.NI(webRequest.getParameter("limit"), 10);

        return new PageDb(page, limit);
    }
}
